import BaseController from './base';

export default class UserController extends BaseController {

  public async login() {
    const { ctx, service } = this;
    try {
      const { email, password } = ctx.request.body;
      if (!email) return this.fail(400, '邮箱填写不正确！');
      if (!password) return this.fail(400, '密码不正确！');
      const data = await service.user.login(email, password);
      if (data.err) return this.fail(data.status, data.err);
      if (data.token) this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async register() {
    const { ctx, service } = this;
    try {
      const { username, password, email } = ctx.request.body;
      if (!username) return this.fail(400, '用户名不能为空！');
      if (!email) return this.fail(400, '邮箱不能为空！');
      if (!password) return this.fail(400, '密码不能为空！');
      const data = await service.user.register(username, password, email);
      if (data.err) return this.fail(data.status, data.err);
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async findUser() {
    const { ctx, service } = this;
    try {
      const { username } = ctx.params;
      const data = await service.user.findUser(username);
      if (data.err) return this.fail(400, '用户不存在');
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async getUserPages() {
    const { ctx, service } = this;
    try {
      const limit = parseInt(ctx.query.limit) || 1;
      const page = parseInt(ctx.query.page) || 1;
      const offset = limit * (page - 1);
      const data = await service.user.getUserPages({ limit, offset });
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }

  public async update() {
    const { ctx, service } = this;
    try {
      const options = ctx.request.body;
      const data = await service.user.update(options);
      if (data.err) return this.fail(400, '参数错误');
      this.success(data);
    } catch (error) {
      ctx.throw(JSON.stringify(error), 400);
    }
  }
}
